package ru.cjay.loading{

import com.adobe.serialization.json.JSON;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;


public class JSONLoader extends EventDispatcher {
    private var _url:String;
    private var _handler:Function;

//    Флаг наличия процесса загрузки

    private var _progress:int = 0;
    private var _totalBytes:int = 0;
    private var _loadedBytes:int = 0;

    public function JSONLoader() {
    }

//    Вызывается при каждом кадре для подсчёта процента загруженного.
    private function onUpdate(event:ProgressEvent):void
    {
        var total:int = 0;
        var loaded:int = 0;

        _totalBytes     =event.bytesTotal;
        _loadedBytes    =event.bytesLoaded;
        _progress = loaded/total;
        event.stopImmediatePropagation();
        dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS,true,true,_totalBytes,_loadedBytes));
    }

    public function loadJSON(p_url:String, p_handler:Function = null):void
    {
        _url = p_url;
        _handler = p_handler;

        var request:URLRequest = new URLRequest(_url);
        SafeConnection.getInstance().makeSafe(request,onComplete,onUpdate,URLLoaderDataFormat.TEXT);
        return;
    }

    private function onComplete(event:Event):void
    {
        var data:Object = JSON.decode(event.target.data);
        event.stopImmediatePropagation();

        if (_handler!=null){
            _handler(data);
        }
        dispatchEvent(new Event(Event.COMPLETE));
    }

    private function onProgress(event:ProgressEvent):void {

    }
}
}